import Vue from 'vue'
import Vuex from 'vuex'

//1.安装vuex
Vue.use(Vuex)

 //保存购物车商品信息
const state={
  carGoods:[],
}
//2.创建store对象
const store = new Vuex.Store({
  state,
  //1.mutations的唯一目的就是修改state中的状态
  //2.mutatios的每个方法尽可能完成的事件单一一点
  //3.actions:
     //1.做异步操作，2.在action中进行条件判断
  actions:{
    judgeProduct(context,product){
      let list=state.carGoods;
      for(let i in list){
          if(list[i].iid==product.iid){
              context.commit("addCount",i);
              return;
          } 
      }
      context.commit("addProduct",product);
      console.log(state.carGoods)
  }
  },
  mutations:{
    addCount(state,index){
      state.carGoods[index].count++
    },
    addProduct(state,product){
        product.index=state.carGoods.length;
        state.carGoods.push(product);
    },
    modifyChecked(state,index){
      state.carGoods[index].checked = !state.carGoods[index].checked;
    },
    /**反选 */
    unAllSelected(state){
        state.carGoods.map(item=>{
            return item.checked=false;
        })
    },
    allSelected(state){
        state.carGoods.map(item=>{
            return item.checked=true;
        })
    },
  },
  getters:{
    totalprice(state){
        if(state.carGoods.length==0)return 0;
        return state.carGoods.filter(item=>{
            return item.checked;
        }).reduce((pre,item)=>{
            return pre+item.lowNowPrice*item.count;
        },0)
        
    },
    cartLength(state){
        if(state.carGoods.length==0)return 0;
        return state.carGoods.filter(item=>{
            return item.checked;
        }).length;
    },
    allLength(state){
        return state.carGoods.length;
    }
  }
  })

export default store